package graduation.claf.service;

import graduation.claf.dao.AccountMapper;
import graduation.claf.dao.BookMapper;
import graduation.claf.dao.OwnershipMapper;
import graduation.claf.dao.UserMapper;
import graduation.claf.pojo.Account;
import graduation.claf.pojo.Book;
import graduation.claf.pojo.Ownership;
import graduation.claf.pojo.User;
import graduation.claf.service.ifs.IUserService;
import graduation.claf.tools.BookTypeCode;
import graduation.claf.tools.DateUtil;
import graduation.claf.tools.ResponseCode;
import graduation.claf.utils.ServerResponse;
import graduation.claf.vo.UserVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;

import static graduation.claf.tools.Tool.createUUID;

@Service
public class UserService implements IUserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    BookMapper bookMapper;
    @Autowired
    OwnershipMapper ownershipMapper;
    @Autowired
    AccountMapper accountMapper;

    //用户登陆逻辑
    @Override
    public ServerResponse loginLogic(String username, String password) {
        //判断账号密码是否为空
        if (StringUtils.isBlank(username)){
            return ServerResponse.createServerResponseByFail(ResponseCode.USERNAME_NOT_EMPTY.getCode(),
                    ResponseCode.USERNAME_NOT_EMPTY.getMsg());
        }
        if (StringUtils.isBlank(password)){
            return ServerResponse.createServerResponseByFail(ResponseCode.PASSWORD_NOT_EMPTY.getCode(),
                    ResponseCode.PASSWORD_NOT_EMPTY.getMsg());
        }
        //判断账号是否存在
        Integer count = userMapper.findByUsername(username);
        if (count == 0){
            return ServerResponse.createServerResponseByFail(ResponseCode.USER_NOT_EXISTS.getCode(),
                    ResponseCode.USER_NOT_EXISTS.getMsg());
        }
        //验证账号密码是否正确
        //密码用MD5加密过
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        User user = userMapper.findByUsernameAndPassword(username,password);
        if (user == null){
            return ServerResponse.createServerResponseByFail(ResponseCode.PASSWORD_ERROR.getCode(),
                    ResponseCode.PASSWORD_ERROR.getMsg());
        }
        return ServerResponse.createServerResponseBySuccess(convert(user),
                ResponseCode.LOGIN_SUCCESS.getMsg());
    }

    //User类转UserVO
    private UserVO convert(User user){
        UserVO userVO = new UserVO();
        userVO.setId(user.getId());
        userVO.setUsername(user.getUsername());
        userVO.setUserpic(user.getUserpic());
        userVO.setEmail(user.getEmail());
        userVO.setTel(user.getTel());
        userVO.setCreatetime(DateUtil.date2String(user.getCreatetime()));
        userVO.setUpdatetime(DateUtil.date2String(user.getUpdatetime()));
        return userVO;
    }

    //用户注册逻辑
    @Override
    public ServerResponse registerLogic(User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        String email = user.getEmail();
        String tel = user.getTel();

        if (user == null||StringUtils.isBlank(username)||
        StringUtils.isBlank(password)||StringUtils.isBlank(tel)||
        StringUtils.isBlank(email)){
            return ServerResponse.createServerResponseByFail(ResponseCode.PARAMETER_NOT_EMPTY.getCode(),
                    ResponseCode.PARAMETER_NOT_EMPTY.getMsg());
        }

        Integer count = userMapper.findByUsername(username);
        if (count != 0){
            return ServerResponse.createServerResponseByFail(ResponseCode.USERNAME_ALREADY_EXISTS.getCode(),
                    ResponseCode.USERNAME_ALREADY_EXISTS.getMsg());
        }

        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        user.setId(createUUID());
        Book book = new Book(createUUID(), BookTypeCode.DEFAULT.getName()
                ,user.getId(),BookTypeCode.DEFAULT.getCode(),1,
                null,-1d,null,null);
        Account account = new Account(user.getId(),0d,0d,0d,0d,0d,0d);
        try {
            userMapper.insert(user);
            bookMapper.insert(book);
            Ownership ownership = new Ownership(book.getId(),user.getId(),"creator");
            ownershipMapper.insert(ownership);
            accountMapper.insert(account);
        }catch (Exception e){
            e.printStackTrace();
            userMapper.deleteByPrimaryKey(user.getId());
            bookMapper.deleteByPrimaryKey(book.getId());
            ownershipMapper.deleteByPrimaryKey(user.getId(),book.getId());
            accountMapper.deleteByPrimaryKey(user.getId());
            return ServerResponse.createServerResponseByFail(ResponseCode.REGISTER_FAIL.getCode(),
                    ResponseCode.REGISTER_FAIL.getMsg());
        }
        return ServerResponse.createServerResponseBySuccess(convert(user),
                ResponseCode.REGISTER_SUCCESS.getMsg());
    }

    @Override
    public ServerResponse getBookInfo(String bookId) {
        Hashtable<String,String> hashtable= new Hashtable<>();
        List<User> users = userMapper.getUserWithBookId(bookId);
        for (int i=0;i<users.size();i++){
            hashtable.put(users.get(i).getId(),users.get(i).getUsername());
        }
        return ServerResponse.createServerResponseBySuccess(hashtable);
    }
}
